<template>
  <el-dialog
    top="1vh"
    :visible.sync="_centerDialogVisible"
    width="90%"
    center
    :append-to-body="false"
  >
    <!-- pdf -->
    <div v-if="fileType==='pdf'">
      <div>
        <pdf
          :page="pageNum"
          :src="filesUrl"
          @num-pages="pageTotalNum=$event"
          @loaded="loadPdfHandler"
        ></pdf>
      </div>
      <div style="text-align:center">
        <div class="pdfPage">
          <el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
          <div class="pdfPageNum">{{ pageNum }} / {{ pageTotalNum }}</div>
          <el-button type="primary" size="mini" @click="nextPage">下一页<i
            class="el-icon-arrow-right el-icon--right"
          ></i></el-button>
        </div>
      </div>
    </div>
    <!-- word -->
    <div v-else-if="fileType==='word' || fileType === 'docx' || fileType === 'doc' " class="wordView">
      <div class="word" id="wordView"></div>
    </div>
    <!-- excel -->
    <div v-else-if="fileType==='excel'|| fileType === 'xlsx' ">
      <div id="tableExcel" v-html="excelHtml" class="tableExcel"></div>
    </div>
    <div v-else>
      <img :src="this.filesUrl" alt="" width="100%" height="100%">
    </div>
  </el-dialog>
</template>

<script>
import pdf from 'vue-pdf'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import mammoth from 'mammoth'

let docx = require('docx-preview')
export default {
  name: 'index',
  components: {
    pdf
  },
  props:{
    centerDialogVisible:{
      type:Boolean,
      default: false
    },
    filesUrl:{
      type:String,
      default: ''
    },
  },
  data() {
    return {
      // 预览附件
      modalPreview: false,
      //excel
      excelHtml: '',
      // 数据
      workbook: {},
      // 表名称集合
      sheetNames: [],
      // 激活项
      sheetNameActive: '',
      // 当前激活表格
      SheetActiveTable: '',
      // pdf文件页码
      pageNum: 1,
      // pdf文件总页数
      pageTotalNum: 1,
      // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
      loadedRatio: 0,
      pdfUrl: '',
      imgUrl: '',
      labelStyle: {
        'width': '120px',
        'text-align': 'right',
        'padding-bottom': '20px'
      },
      fileType:''
    }
  },
  watch: {
    centerDialogVisible: {
      handler(newVal) {
        if (!newVal){
         this.$emit( 'update:filesUrl','' )
        }
      },
      deep: true,
      immediate:true
    },
    filesUrl:{
      handler(newVal){
        this.fileType = this.filesUrl.substring(this.filesUrl.lastIndexOf(".") + 1);
        if (this.fileType === 'doc' || this.fileType === 'docx'){
          this.previewWord(this.filesUrl)
        }
      }
    }
},
  computed:{
    _centerDialogVisible:{
      get () {
        return this.centerDialogVisible
      },
      set (newVal) {
        this.$emit('update:centerDialogVisible',newVal)
      }
    }
  },
  methods: {
    //预览word
    previewWord() {
      // this.previewType = 1;
      axios({
        method: "post",
        responseType: "arraybuffer", // 因为是流文件，所以要指定blob类型
        headers: {Authorization: 'Bearer ' + getToken()},
        url: process.env.VUE_APP_BASE_API + "/farm/rule/getWord?url=" + this.filesUrl, // 自己的服务器，提供的一个word下载文件接口
      }).then(res => {
        let content = res.data;
        let blob = new Blob([content], {type: "application/pdf"});
        let reader = new FileReader();
        reader.readAsArrayBuffer(blob);
        reader.onload = function (e) {
          var arrayBuffer = e.target.result; //arrayBuffer
          mammoth.convertToHtml({arrayBuffer: arrayBuffer}).then(displayResult).done();
        };

        function displayResult(result) {
          document.getElementById("wordView").innerHTML = result.value.replaceAll("<img", "<img style='width:100%'")
            .replaceAll("<table", "<table style='width: 100%;border-right: 1px solid  #e8eaec;border-bottom:1px solid  #e8eaec;border-collapse: collapse;margin: auto 0px;text-align: center;'")
            .replaceAll("<td", "<td style='border-left: 1px solid  #e8eaec;border-top: 1px solid  #e8eaec;white-space: nowrap;padding: .5rem;text-overflow: ellipsis;overflow: hidden;'")
            .replaceAll("<tr", "<tr style='font-weight: bold;font-size:13px;'")
        }

      });
    },
    //pdf上一页
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },
    //pdf下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    loadPdfHandler(e) {
      this.pageNum = 1 // 加载的时候先加载第一页
    },
    change(fileName){
      // docx
      if (this.fileType === 'docx' || this.fileType === 'doc') {
        this.previewWord(this.filesUrl);
      }
      // pdf
      else if (this.fileType === 'pdf') {
        this.pdfUrl = this.filesUrl;
      }
    },
  }
}
</script>

<style scoped>

.pdfPage {
  margin: 0 auto;
}
.pdfPageNum {
  display: inline-block;
  height: 28px;
  color: #409EFF;
  margin: 12px 12px;
  top: 20px;
  font-size: 18px;
}

</style>
